//
//  UIImage+TintColor.m
//
//
//  Created by Conner Wu.
//  Copyright (c) 2015年 Conner Wu. All rights reserved.
//

#import "UIImage+TintColor.h"

@implementation UIImage (TintColor)

- (UIImage *)imageWithTintColor:(UIColor *)tintColor
{
    return [self imageWithTintColor:tintColor blendMode:kCGBlendModeDestinationIn];
}

- (UIImage *)imageWithGradientTintColor:(UIColor *)tintColor
{
    return [self imageWithTintColor:tintColor blendMode:kCGBlendModeOverlay];
}

- (UIImage *)imageWithTintColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode
{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
    [tintColor setFill];
    CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
    UIRectFill(bounds);
    [self drawInRect:bounds blendMode:blendMode alpha:1.0f];
    if (blendMode != kCGBlendModeDestinationIn) {
        [self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
    }
    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tintedImage;
}

+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
- (UIImage *)imageWithCompressedMaxSize:(CGFloat)maxSize{
    
    if (self.size.width <= maxSize && self.size.height <= maxSize) {
        /**图片不用压缩直接返回原图*/
        return self;
    }
    
    CGSize newSize = [self imageSizeWithMaxSize:maxSize];
    
    UIGraphicsBeginImageContext(newSize);

    [self drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}
- (CGSize)imageSizeWithMaxSize:(CGFloat)maxSize{
    CGFloat imageWith   = 0.0f;
    CGFloat imageHeight = 0.0f;
    if (self.size.width >= self.size.height) {
        /**宽 > 高*/
        imageWith = maxSize;
        imageHeight = self.size.height / self.size.width * imageWith;
    }else{
        imageHeight = maxSize;
        imageWith   = self.size.width / self.size.height * imageHeight;
    }
    
    return CGSizeMake(imageWith, imageHeight);
}
@end
